"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 防篡改
Case Name   : 用户权限分配遵从责任分离原则
Create At   : 2022/3/10
Owner       : @daiguatutu
Description :
    1.设置参数并重启数据库enableSeparationOfDuty=on
    2.创建三个不同权限的用户(SYSADMIN/CREATEROLE/AUDITADMIN)
    3.SYSADMIN权限用户创建/删除数据库
    4.SYSADMIN权限用户创建用户,查看/删除审计日志
    5.AUDITADMIN权限用户，删除审计日志
    6.AUDITADMIN权限用户，创建数据库和用户
    7.AUDITADMIN权限用户,查看审计日志
    8.清理环境
Expect      :
    1.成功
    2.成功
    3.成功
    4.失败
    5.成功
    6.失败
    7.成功
    8.清理环境成功
History     :
    Modified by @songjing20 at 2023/4/23: 优化step5、step7删除/查询审计日志sql语句，
    更正step6的expect描述
"""

import os
import unittest

from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import Node
from yat.test import macro


class Security(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.pri_node = Node('PrimaryDbUser')
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.constant = Constant()
        self.common = Common()
        self.u_name1 = 't_security_authen_account_0007_01'
        self.u_name2 = 't_security_authen_account_0007_02'
        self.u_name3 = 't_security_authen_account_0007_03'
        self.u_name4 = 't_security_authen_account_0007_04'
        self.db_name = 'db_security_authen_account_0007'
        self.default_value1 = self.common.show_param('enableSeparationOfDuty')

    def test_security(self):
        text = '-----查看当前时间; expect:成功-----'
        self.log.info(text)
        sql_time = f"select sysdate;"
        result = self.pri_sh.execut_db_sql(sql_time)
        self.log.info(result)
        time_start = result.splitlines()[-2].strip()

        text = '-----step1：设置参数并重启数据库enableSeparationOfDuty=on; ' \
               'expect:成功-----'
        self.log.info(text)
        mod_msg = self.pri_sh.execute_gsguc('set',
                                            self.constant.GSGUC_SUCCESS_MSG,
                                            'enableSeparationOfDuty=on')
        self.assertTrue(mod_msg, '执行失败:' + text)
        result = self.pri_sh.restart_db_cluster()
        self.assertTrue(result, '执行失败' + text)

        text = '-----step2：创建三个不同权限的用户(SYSADMIN/CREATEROLE/AUDITADMIN) ' \
               'expect:成功-----'
        self.log.info(text)
        create_cmd = f"drop database if exists {self.db_name};" \
            f"drop user if exists {self.u_name1}," \
            f"{self.u_name2},{self.u_name3},{self.u_name4} cascade; " \
            f"create user {self.u_name1} sysadmin " \
            f"password '{macro.GAUSSDB_INIT_USER_PASSWD}';" \
            f"create user {self.u_name2} createrole " \
            f"password '{macro.GAUSSDB_INIT_USER_PASSWD}';" \
            f"create user {self.u_name3} auditadmin " \
            f"password '{macro.GAUSSDB_INIT_USER_PASSWD}';"
        msg = self.pri_sh.execut_db_sql(create_cmd)
        self.log.info(msg)
        self.assertIn(self.constant.DROP_DATABASE_SUCCESS, msg,
                      '执行失败:' + text)
        self.assertIn(self.constant.DROP_ROLE_SUCCESS_MSG, msg,
                      '执行失败:' + text)
        self.assertEqual(3, msg.count(self.constant.CREATE_ROLE_SUCCESS_MSG),
                         '执行失败:' + text)

        text = f'-----step3：SYSADMIN权限用户创建/删除数据库; expect:成功-----'
        self.log.info(text)
        sql = f"create database {self.db_name};" \
            f"drop database {self.db_name};"
        connect = f'-U {self.u_name1} -W {macro.GAUSSDB_INIT_USER_PASSWD}'
        msg = self.pri_sh.execut_db_sql(sql, sql_type=connect)
        self.log.info(msg)
        self.assertIn(self.constant.DROP_DATABASE_SUCCESS, msg,
                      '执行失败:' + text)
        self.assertIn(self.constant.CREATE_DATABASE_SUCCESS, msg,
                      '执行失败:' + text)

        text = '-----step4：SYSADMIN权限用户创建用户,查看/删除审计日志 expect:失败-----'
        self.log.info(text)
        sql = f"create user {self.u_name4} identified by " \
            f"'{macro.GAUSSDB_INIT_USER_PASSWD}';" \
            f"SELECT pg_delete_audit('{time_start}','2999-01-01');" \
            f"SELECT pg_query_audit('{time_start}','2999-01-01');"
        msg = self.pri_sh.execut_db_sql(sql, sql_type=connect)
        self.log.info(msg)
        self.assertEqual(3, msg.count('ermission denied'), '执行失败:' + text)

        text = '-----step5：AUDITADMIN权限用户，删除审计日志 expect:成功-----'
        self.log.info(text)
        sql = f"SELECT pg_delete_audit('{time_start}', sysdate);"
        connect = f'-U {self.u_name3} -W {macro.GAUSSDB_INIT_USER_PASSWD}'
        msg = self.pri_sh.execut_db_sql(sql, sql_type=connect)
        self.log.info(msg)
        self.assertIn('1 row', msg, '执行失败:' + text)

        text = '-----step6：AUDITADMIN权限用户，创建数据库和用户 expect:失败-----'
        self.log.info(text)
        sql = f"create database {self.db_name};" \
            f"create user {self.u_name4} identified by " \
            f"'{macro.GAUSSDB_INIT_USER_PASSWD}';"
        msg = self.pri_sh.execut_db_sql(sql, sql_type=connect)
        self.log.info(msg)
        self.assertEqual(2, msg.count('ermission denied'), '执行失败:' + text)

        text = '-----step7：AUDITADMIN权限用户，查看审计日志 expect:成功-----'
        self.log.info(text)
        sql = f"select * from pg_query_audit('{time_start}','2999-01-01') " \
            f"where username ='{self.u_name3}';"
        msg = self.pri_sh.execut_db_sql(sql, sql_type=connect)
        self.log.info(msg)
        self.assertIn(f'logout db({self.pri_node.db_name}) success', msg,
                      '执行失败:' + text)

    def tearDown(self):
        self.log.info('-----step8：清理环境-----')
        text1 = '-----删除用户和表 expect:成功-----'
        self.log.info(text1)
        drop_cmd = f"drop database if exists {self.db_name};" \
            f"drop user if exists {self.u_name1}," \
            f"{self.u_name2},{self.u_name3},{self.u_name4} cascade;"
        drop_msg = self.pri_sh.execut_db_sql(drop_cmd)
        self.log.info(drop_msg)

        text2 = '-----修改参数enableSeparationOfDuty为初始值并重启数据库 expect:成功-----'
        self.log.info(text2)
        mod_msg1 = self.pri_sh.execute_gsguc('set',
                                             self.constant.GSGUC_SUCCESS_MSG,
                                             f'enableSeparationOfDuty='
                                             f'{self.default_value1}')
        restart_res = self.pri_sh.restart_db_cluster()

        self.log.info('-----断言tearDown执行成功-----')
        self.assertIn(self.constant.DROP_DATABASE_SUCCESS, drop_msg,
                      '执行失败:' + text1)
        self.assertIn(self.constant.DROP_ROLE_SUCCESS_MSG, drop_msg,
                      '执行失败:' + text1)
        self.assertTrue(mod_msg1, '执行失败:' + text2)
        self.assertTrue(restart_res, '执行失败:' + text2)
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
